package com.gitee.ywj14352.action.echo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * EchoClient 向外输出单个信息
 * @author yangwenjie.a
 */
public class EchoClient {
    public static final Logger LOGGER = LoggerFactory.getLogger(EchoClient.class);
    private final int port;
    private final String host;


    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }


    public void start() {

        Bootstrap bootstrap = new Bootstrap();
        EventLoopGroup clientGroup = new NioEventLoopGroup();

        try {

            bootstrap.remoteAddress(host, port);

            bootstrap.group(clientGroup);

            bootstrap.channel(NioSocketChannel.class);

            bootstrap.handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new EchoClientHandler());
                }
            });

            ChannelFuture future = bootstrap.connect().sync();

            future.channel().closeFuture().sync();

        } catch (Exception e) {
            LOGGER.error("start client has error ", e);
        } finally {
            clientGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {

        EchoClient echoClient = new EchoClient("127.0.0.1", 8990);

        echoClient.start();
    }


}
